package com.choudou5.nlp.config;

import cn.hutool.core.collection.CollUtil;
import com.choudou5.solr.util.notice.NoticeUtil;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @name AppKey 池
 * @author choudou5
 * @date 2018-08-07
 */
public class AppKeyPool {

    private static final Map<String, List<AppKeyBean>> pool = new ConcurrentHashMap<>();

    /**
     * 初始化 渠道配置
     * @param channel
     * @param list
     */
    public static void initByChannel(String channel, List<AppKeyBean> list){
        if(CollUtil.isNotEmpty(list)){
            pool.put(channel, list);
        }else{
            NoticeUtil.send("未配置 "+channel+" 渠道AppKey.");
        }
    }

    /**
     * 获取 渠道 AppKey
     * @param channel
     * @return
     */
    public static AppKeyBean getByChannel(String channel){
        List<AppKeyBean> list = pool.get(channel);
        if(CollUtil.isNotEmpty(list)){
            for (AppKeyBean bean : list) {
                if(!bean.isBusy() && bean.getRemainCount() > 10){
                    bean.setBusy(true);
                    return bean;
                }
            }
            NoticeUtil.send(channel+" 渠道AppKey配置已使用完，请更换配置.");
        }
        return null;
    }

}
